import { connect } from 'umi';
import { ContractManageAPI } from '../common/type';
import { Col, Form, Row, Spin, message } from 'antd';
import { ConractControllerContext, IContractsActionEnum, useContractsReducer } from '../common';
import { useEffect, useState } from 'react';
import { contractChildervice, getMcontractByIDService, submitRecordContractService, addContractAttachService } from '../services';
import '../common/styles.less';
import { DetailInfoViewTabs } from './DetailInfoViewTabs';
import { getColorTextLoadMap, getKeyRouter, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { readReadShowFileService } from '@/services/BaseLayout';
import { history } from 'umi';

const ContractDetailInfoView: React.FC<ContractManageAPI.IContractDetailInfoView> = ({ curRes, locationProps }) => {
  /** 表单 */
  const [contractForm] = Form.useForm();

  /** 样式根名称 */
  const styleFixCls = 'contract-styfixcls-';

  /** 获取reducets */
  const { counterpartRows, contractTempRow, contractDispatch, partyFirstSelectRows } = useContractsReducer();

  /** 保存当前页面页签 */
  const [tabPaneKeysInfo, setTabPaneKeysInfo] = useState<Record<string, any>[]>([]);

  /** 保存原合同信息 */
  const [saveOldContractInfo, setSaveOldContractInfo] = useState<Record<string, any>>({});

  /** 添加编辑回调 */
  const updateCallback = (res: any, clickType: boolean) => {
    if (res && res?.msgFlag) {
      if (clickType) {
        if (locationProps?.state?.updateType == 'UpdateRepairAdd') {
          history.push({
            pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'detail',
              id: res?.obj?.id,
              pageInfo: res?.obj,
              pIDDetailInfo: {
                ...res?.obj,
              },
              delRouterName: history.location.pathname, //必传,要删除的路由名称
              returnPathName: locationProps?.state?.returnPathName,
            },
          });
        } else {
          history.push({
            pathname: `/contractController/edit/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'add',
              id: res?.obj?.id,
              delRouterName: history.location.pathname, //必传,要删除的路由名称
              returnPathName: locationProps?.state?.returnPathName,
            },
          });
        }
      } else {
        message.success(res?.msg);
        reloadDetailInfo();
      }
    } else {
      message.error(res?.msg);
    }
  };
  /** 补录提交接口 */
  const { submitRecordContractLoading, submitRecordContractRun } = submitRecordContractService(updateCallback);

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      contractDispatch({
        type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
        payload: res?.obj?.oppositeList?.length > 0 ? res?.obj?.oppositeList : [],
      });

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {},
      });

      // 处理合同主体信息
      contractDispatch({
        type: IContractsActionEnum.SELECT_PARTYALIST,
        payload: [
          {
            oppositeName: res?.obj?.oppositeName,
            oppositeID: res?.obj?.id,
            // phoneMobile: res?.obj?.contactMobile,
            // contactName: res?.obj?.contactName,
            creditID: res?.obj?.creditID,
            bankName: res?.obj?.bankName,
            bankAccount: res?.obj?.bankAccount,
            registerPhone: res?.obj?.registerPhone,
            workAddress: res?.obj?.workAddress,
            partyId: `party-first-${getKeyRouter()}`,
          },
        ],
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDInfo, getMcontractByIDLoading, getMcontractByIDRun, reloadDetailInfo } = getMcontractByIDService(detailsCallback);

  /** 合同详情时添加附件 */
  const { addContractAttachLoading, addContractAttachRun } = addContractAttachService();

  /** 处理变更或者解除tab数据 */
  const handleModifyPanes = (dataList: Record<string, any>[], dataType: boolean) => {
    let paneKeys: Record<string, any>[] = [];
    dataList?.forEach((item: any, index: number) => {
      paneKeys?.push({
        label: `${dataType ? '变更' : '解除'}合同${dataList?.length > 1 ? '-' + (index + 1) : ''}`,
        key: item?.id,
        paneType: dataType ? 'modifyPane' : 'breakPane',
      });
    });
    return paneKeys;
  };

  /** 获取变更或解除合同个数回调 */
  const childManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      let allTabPanes: Record<string, any>[] = [];
      let modifyPanes: Record<string, any>[] = [];
      let breakPanes: Record<string, any>[] = [];

      allTabPanes?.push({
        label: '主合同详情',
        // key: locationProps?.state?.pageInfo?.pID,
        key: locationProps?.state?.pageInfo?.pID ? locationProps?.state?.pageInfo?.pID : locationProps?.state?.id,
        paneType: 'mainPane',
      });

      // 获取变更合同
      const modifyList: Record<string, any>[] = res?.obj?.filter((itemModify: any) => itemModify?.changeWay == 0);
      if (modifyList?.length > 0) {
        modifyPanes = handleModifyPanes(modifyList, true);
      }

      // 获取解除合同
      const breakList: Record<string, any>[] = res?.obj?.filter((itemBreak: any) => itemBreak?.changeWay == 1);
      if (breakList?.length > 0) {
        breakPanes = handleModifyPanes(breakList, false);
      }

      allTabPanes = [...allTabPanes, ...modifyPanes, ...breakPanes];

      if (locationProps?.state?.pIDDetailInfo.state != `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1000`) {
        // 添加履约记录
        allTabPanes?.push({
          label: '履约记录',
          key: locationProps?.state?.pIDDetailInfo?.contractCode + '_nodePane',
          paneType: 'nodePane',
        });

        // // 添加收支记录
        // allTabPanes?.push({
        //   label: '收支记录',
        //   key: locationProps?.state?.pIDDetailInfo?.contractCode,
        //   paneType: 'agreePane',
        // });
      }

      setTabPaneKeysInfo(allTabPanes);
    } else {
      message.error(res?.msg);
    }
  };

  /**  获取管理页数据 */
  const { loading, getChildManage } = contractChildervice(childManageCallback);

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      // if (locationProps?.state?.pageInfo?.pID) {
      getChildManage({
        // pID: locationProps?.state?.pageInfo?.pID
        pID: locationProps?.state?.pageInfo?.pID ? locationProps?.state?.pageInfo?.pID : locationProps?.state?.id,
      });
      // } else {
      //   setTabPaneKeysInfo([{
      //     label: "基本信息",
      //     key: locationProps?.state?.id,
      //     paneType: "mainPane"
      //   }])
      // }

      if (locationProps?.state?.pIDDetailInfo?.id) {
        const infoObj: Record<string, any> = { ...locationProps?.state?.pIDDetailInfo };
        setSaveOldContractInfo(infoObj);
      }
    }
  }, [locationProps?.state?.id]);

  /** 轻阅读预览 */
  const { readReadShowFileRun, readReadShowFileLoading } = readReadShowFileService();

  return (
    <ConractControllerContext.Provider
      value={{
        styleFixCls,
        curRes,
        locationID: locationProps?.state?.id,
        contractDispatch,
        pageType: locationProps?.state?.pageType,
        counterpartRows,
        contractTempRow,
        materialCheckRows: [],
        contractForm,
        contractDetailInfo: {
          ...getMcontractByIDInfo,
          supplyTypeName: getColorTextLoadMap(getMcontractByIDInfo?.supplyTypeName)?.colorText,
          procureRealName: getColorTextLoadMap(getMcontractByIDInfo?.procureRealName)?.colorText,
        },
        contarctJsonList: {},
        reloadDetail: reloadDetailInfo,
        updteAddOrEdit: {
          addContractRun: () => {},
          editContractRun: () => {},
          editRecordContractRun: () => {},
          submitRecordContractRun,
          addContractAttachRun,
          addAndSubmitContractRun: () => {},
        },
        oldContractForm: {},
        oldContractInfo: {
          ...saveOldContractInfo,
        },
        locationState: locationProps?.state,
        getDetailInfoRun: getMcontractByIDRun,
        partyFirstSelectRows,
        readReadShowFileRun,
      }}
    >
      <Spin spinning={loading || getMcontractByIDLoading || readReadShowFileLoading || submitRecordContractLoading || addContractAttachLoading}>
        <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
          <Col span={24} className={`${styleFixCls}row-col`}>
            <DetailInfoViewTabs tabPaneKeys={tabPaneKeysInfo} />
          </Col>
        </Row>
      </Spin>
    </ConractControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(ContractDetailInfoView);
